<template>
    <div class="edit" v-if="show">

        <div id="edit" :class="edit_class">

            <!--S标题-->
            <h2>
                <span v-if="coupon_id">编辑卡券</span>
                <span v-else>创建卡券</span>
                <i
                        class="close iconfont icon-guanbi"
                        @click="$emit('close')"
                >
                </i>
            </h2>
            <!--E标题-->

            <!--S表单-->
            <div id="form">
                <cube-scroll>
                    <cube-form
                            ref="form"
                            :model="model"
                            :schema="schema"
                            @submit="submit"
                    >
                    </cube-form>
                    <!--S提交按钮-->
                    <div class="submit-button">
                        <cube-button
                                @click="$refs.form.submit()"
                                :disabled="submitting"
                        >
                            <template v-if="this.coupon_id === ''">创建</template>
                            <template v-else>修改</template>
                        </cube-button>
                    </div>
                    <!--E提交按钮-->
                </cube-scroll>
            </div>
            <!--E表单-->

        </div>

    </div>
</template>

<script>
import FormMedia from "@/form/form-meida"
import FormCouponType from "./form/form-coupon-type"
import FormDj from "./form/form-dj"
import FormMj from "./form/form-mj"
import FormDh from "./form/form-dh"
import FormZk from "./form/form-zk"
import FormRc from "./form/form-rc"
import FormTimeType from "./form/form-time-type"
import FormDate from "@/form/form-date"
import Util from "@/util/util.js"
export default {
    name: "edit",
    data () {
        return {
            // id 编辑区域class，控制打开关闭的动画
            edit_class: "close",
            model: {
                name: '',
                address: '',
                cover: [],
                type: 'dj',
                type_value: {},
                time_type: '1',
                time: '',
                detail: ''
            },
            schema: {
                fields: [
                    {
                        type:'input',
                        modelKey:'name',
                        key: 'name',
                        label:'卡券名字',
                        props: {
                            placeholder: '请输入卡券名字'
                        },
                        rules: {
                            required:true,
                            max: 30
                        },
                        messages: {
                            required: '请设置卡券名字',
                            max: '长度不能大于30字符'
                        }
                    },
                    {
                        type: 'textarea',
                        modelKey: 'address',
                        key: 'address',
                        label: '核销地址',
                        props: {
                            placeholder: '请输入卡券核销地址',
                            maxlength: 255
                        },
                        rules: {
                            required:true,
                            max: 255
                        },
                        messages: {
                            required: '请输入核销地址'
                        }
                    },
                    {
                        type: FormMedia,
                        modelKey: 'cover',
                        key: 'cover',
                        label:'卡券封面',
                        props: {
                            number: 1
                        },
                        events: {
                            remove:(index)=>{
                                this.model.cover.splice(index,1)
                            }
                        }
                    },
                    {
                        type: FormCouponType,
                        modelKey: 'type',
                        key: 'type',
                        label: '卡券类型'
                    },
                    {
                        type: FormTimeType,
                        modelKey: 'time_type',
                        key: 'time_type',
                        label: '时间限制'
                    },
                    {
                        type: 'textarea',
                        modelKey: 'detail',
                        key: 'detail',
                        label: '说明(核销规则)',
                        props: {
                            placeholder: '请输入卡券核销地址',
                            maxlength: 10000,
                            indicator: false
                        },
                        rules: {
                            required: true
                        },
                        messages: {
                            required: '请输入卡券核销规则'
                        }
                    }
                ]
            },
            // 是否提交中
            submitting: false
        }
    },
    props: {
        // 区域显示状态
        show: {
            type: Boolean,
            default: false
        },
        // 卡券id
        coupon_id: {
            type: String,
            default: ''
        }
    },
    watch: {
        // 显示状态改变
        show() {
            this.toggle()
        },
        "model.type"() {
            this.toggleTypeForm()
        },
        "model.time_type"() {
            this.toggleTimeForm(false)
        }
    },
    mounted() {
        this.toggleTypeForm()
        this.toggleTimeForm(true)
    },
    methods: {
        /**
         * 显示隐藏区域
         */
        toggle() {
            if(this.show) {
                this.reset()
                setTimeout(() => {
                    this.edit_class = 'open'
                },100)
            } else {
                this.edit_class = 'close'
            }
        },
        reset() {
            if(this.coupon_id === ''){
                this.model = {
                    name: '',
                    address: '',
                    cover: [],
                    type: 'dj',
                    type_value: {},
                    time_type: '1',
                    time: '',
                    detail: ''
                }
            } else {
                this.$get("coupon/take",{
                    coupon_id: this.coupon_id
                })
                    .then((res) => {
                        let {code, data} = res.data
                        if(code === 0) {
                            let {name,address,cover,type,type_value,time,time_type,detail} = data
                            this.model = {
                                name,
                                address,
                                cover:cover ? [cover] : [],
                                type,
                                type_value,
                                time_type,
                                time: time,
                                detail: detail.replace(/<br \/>/g,"\n")
                            }
                        }
                    })
            }
        },
        /**
         * 插入优惠券值form
         */
        toggleTypeForm() {
            this.type_value = {}
            let position = this.getTogglePosition("type")
            if(this.schema.fields[position] && this.schema.fields[position].modelKey === 'type_value'){
                this.schema.fields.splice(position,1)
            }
            let push_form = {}
            switch (this.model.type) {
                case 'dj':
                    push_form = {
                        type: FormDj,
                        modelKey: 'type_value',
                        key: 'type_value',
                        label: '代金券金额',
                        trigger: 'change',
                        rules: {
                            custom: (val) => {
                                return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(val.value)
                            }
                        },
                        messages: {
                            custom: '请输入正确的金额'
                        }
                    }
                    this.schema.fields.splice(position,0,push_form)
                    break;
                case 'mj':
                    push_form = {
                        type: FormMj,
                        modelKey: 'type_value',
                        key: 'type_value',
                        label: '满减金额',
                        rules: {
                            value: (val) => {
                                return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(val.face)
                                        &&
                                      /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(val.value)
                            },
                            faceMaxValue: (val) => {
                                return parseFloat(val.face) > parseFloat(val.value)
                            }
                        },
                        messages: {
                            value: '请输入正确的金额',
                            faceMaxValue: '请输入正确的满减金额'
                        }
                    }
                    this.schema.fields.splice(position,0,push_form)
                    break;
                case 'dh':
                    push_form = {
                        type: FormDh,
                        modelKey: 'type_value',
                        key: 'type_value',
                        label: '兑换物品',
                        rules: {
                            value: (val) => {
                                return val.value !== undefined && val.value.trim().length > 0
                            }
                        },
                        messages: {
                            value: '请输入正确的兑换物品'
                        }
                    }
                    this.schema.fields.splice(position,0,push_form)
                    break;
                case 'zk':
                    push_form = {
                        type: FormZk,
                        modelKey: 'type_value',
                        key: 'type_value',
                        label: '卡券折扣',
                        rules: {
                            value: (val) => {
                                return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(val.value)
                            },
                            value_min: (val) => {
                                return val.value !== undefined && parseFloat(val.value) > 0
                            },
                            value_max: (val) => {
                                return val.value !== undefined && parseFloat(val.value) < 10
                            }
                        },
                        messages: {
                            value: '请输入正确的卡券折扣',
                            value_min: '请输入正确的卡券折扣',
                            value_max: '请输入正确的卡券折扣'
                        }
                    }
                    this.schema.fields.splice(position,0,push_form)
                    break;
                case 'rc':
                    push_form = {
                        type: FormRc,
                        modelKey: 'type_value',
                        key: 'type_value',
                        label: '场地',
                        rules: {
                            value: (val) => {
                                return val.value !== undefined && val.value.trim().length > 0
                            }
                        },
                        messages: {
                            value: '请输入正确的场地'
                        }
                    }
                    this.schema.fields.splice(position,0,push_form)
                    break;
            }
        },
        /**
         *插入优惠券过期时间form
         */
        toggleTimeForm(is_create) {
            let position = this.getTogglePosition("time_type")
            if(this.schema.fields[position] && this.schema.fields[position].modelKey === 'time'){
                this.schema.fields.splice(position,1)
            }
            let value = this.model.time_type
            if(value === '2') {
                if(is_create){
                    this.model.time = new Date().getTime() / 1000
                } 
                this.schema.fields.splice(position,0,{
                    type: FormDate,
                    modelKey: 'time',
                    key: 'time',
                    label: '有效时间至',
                    props: {
                        placeholder: '选择时间'
                    },
                    rules: {
                        required: true
                    },
                    messages: {
                        required: '请设置卡券有效期'
                    }
                })
            } else if(value === '3') {
                if(is_create) this.model.time = ''
                this.schema.fields.splice(position,0,{
                    type: 'input',
                    modelKey: 'time',
                    key: 'time',
                    label: '有效天数',
                    props: {
                        placeholder: '领券后几天内有效'
                    },
                    rules: {
                        required: true,
                        integer: (val) => {
                            return Math.abs(val) === parseInt(val)
                        }
                    },
                    messages: {
                        required: '请设置卡券有效天数',
                        integer: '请设置正确的有效天数'
                    }
                })
            }
        },
        /**
         * 传入取消表单组件时获取插入取消的数组下标位置
         * @param model_key 表单的model值
         * @returns {number}
         */
        getTogglePosition(model_key){
            let position = 0
            for(position=0;position<this.schema.fields.length;position++) {
                if(this.schema.fields[position].modelKey === model_key){
                    break;
                }
            }
            return position+1
        },
        /**
         * 提交
         */
        submit(form,model) {
            this.submitting = true
            let data = {}
            for(let item in model) {
                if(item === 'detail') {
                    data[item] = model[item].replace(/\n/g,'<br />')
                } else {
                    data[item] = model[item]
                }
            }
            this.$post("coupon/edit",{
                data,
                coupon_id: this.coupon_id
            })
                .then((res) => {
                    this.submitting = false
                    let { code, data } = res.data
                    if(code === 0){
                        if(this.coupon_id === '') {
                            this.$emit("createSuccess", data)
                        } else {
                            this.$emit("editSuccess")
                        }
                        this.$createToast({
                            type: 'correct',
                            time: 2000,
                            txt: '成功'
                        }).show()
                        // 提示订阅消息
                        this.subscribeMessage() 
                    } else {
                        this.$createToast({
                            type: 'error',
                            time: 2000,
                            txt: '操作失败'
                        }).show()
                    }
                })
        },
        /**
         * 提示订阅消息
         */
        subscribeMessage() {
            if(process.env.NODE_ENV === 'production') {
                let system = Util.getSystemInfo()
                if(Util.versionCompare(system.wx_version,"7.0.12") >= 0) {
                    if (
                        system.client === 'ios' && Util.versionCompare(system.version,"10.3") >= 0
                        ||
                        system.client === 'android' && Util.versionCompare(system.version,"5.0") >= 0
                    ){
                        this.$get('subMessage/testShowSubMessage', {
                            type: 'coupon'
                        })
                            .then((res) => {
                                let {code, data} = res.data
                                if (!code) {
                                    this.$createSubscribe({
                                        is_show: new Date().getTime(),
                                        template_id: data
                                    })
                                }
                            })
                    }
                }
            } else {
                let system = Util.getSystemInfo()
                if (
                    system.client === 'ios' && Util.versionCompare(system.version,"10.3") >= 0
                    ||
                    system.client === 'android' && Util.versionCompare(system.version,"5.0") >= 0
                ){
                    this.$get('subMessage/testShowSubMessage', {
                        type: 'coupon'
                    })
                        .then((res) => {
                            let {code, data} = res.data
                            if (!code) {
                                this.$createSubscribe({
                                    is_show: new Date().getTime(),
                                    template_id: data
                                })
                            }
                        })
                }
            }
        }
    }
}
</script>

<style scoped lang="less" src="./edit.less"></style>
